package org.luceneEngine;

import java.io.FileReader;
import java.io.IOException;

import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.util.Version;


/*
 * Handles Text Documents in a separate thread
 * 
 * Reads in the text document and indexes it
 * 	-> Content is stored in the content field should be searched for using standard analyzer
 *  -> title is the fileName, minus the .txt extension
 *  -> Tag holds the absolute file path
 *  
 * TODO:
 * Probably need to refactor this a bit so that the search functions pass back the file names
 * of matches, instead of a whole bunch of useless content.
 *  -> This way we can display the fileNames in the GUI on the client side and prompt for transfer
 * 
 */
public class LuceneTxtHandler extends GenericLuceneDocumentHandler implements LuceneHandler {

	static Logger logger = Logger.getLogger(LuceneTxtHandler.class.getName());
	// Just set up the private variables for writing and searching
	
	public LuceneTxtHandler(String indexDir) throws IOException{
		super(indexDir);
	}
	
	/*
	 * Add the fields into lucene
	 * Title is the name minus the extension
	 * Contents are the indexed file
	 * Tag is the full filename
	 * @see org.luceneEngine.LuceneHandler#writeContents(java.lang.String, java.lang.String)
	 */
	@Override
	public void writeContents(String fileName, String keyToSearchFor) {
		FileReader fr = null;
		cfg = new IndexWriterConfig(Version.LUCENE_36, analyzer);
		try {
			//If the file has no hits in the index (i.e. it doesn't exist) copy it in
			if(notInIndex(keyToSearchFor)){
				indexWriter = new IndexWriter(dir, cfg);
				Document doc = new Document();
				doc.add(new Field("title", keyToSearchFor, Field.Store.YES, Field.Index.NOT_ANALYZED));
				fr = new FileReader(fileName);
				doc.add(new Field("contents", fr));
				doc.add(new Field("tags", fileName, Field.Store.YES, Field.Index.NOT_ANALYZED));
				indexWriter.addDocument(doc);
				logger.info("Added " + fileName + " to the index");
				indexWriter.close();
			}
			else {
				logger.debug("Not adding: " + fileName + " to the index");
			}
		}
		catch(IOException e){
			logger.warn("Could not add " + fileName + " to the index");
		}

	}



}
